<template>
  <div>
    <h2 style="margin-top: 0;">项目列表</h2>
    <p style="color: #86909c; margin-bottom: 20px;">管理所有评审项目</p>

    <div class="filter-bar">
      <div class="filter-group">
        <el-select v-model="selectedSpecialty" placeholder="专业组" @change="handleFilterChange">
          <el-option label="全部" value=""></el-option>
          <el-option label="油气勘探" value="油气勘探"></el-option>
          <el-option label="油气藏工程" value="油气藏工程"></el-option>
          <el-option label="钻采与地面工程" value="钻采与地面工程"></el-option>
          <el-option label="信息工程" value="信息工程"></el-option>
        </el-select>

        <el-select v-model="selectedLevel" placeholder="申报等级" @change="handleFilterChange">
          <el-option label="全部" value=""></el-option>
          <el-option label="一等奖" value="一等奖"></el-option>
          <el-option label="二等奖" value="二等奖"></el-option>
          <el-option label="三等奖" value="三等奖"></el-option>
        </el-select>

        <el-input
            placeholder="搜索项目名称..."
            prefix-icon="el-icon-search"
            style="width: 250px;"
            v-model="searchKeyword"
            @input="handleSearchInput"
            clearable
        ></el-input>
      </div>

      <div class="action-buttons">
        <el-button type="primary" icon="el-icon-upload" @click="openImportDialog">导入项目</el-button>
        <el-button
            type="danger"
            icon="el-icon-delete"
            @click="batchDeleteProjects"
            :disabled="selectedProjectRows.length === 0"
        >
          批量删除
        </el-button>
      </div>
    </div>

    <div class="card-container">
      <el-table
          :data="filteredProjects"
          border
          style="width: 100%;"
          v-loading="loading"
          element-loading-text="正在加载项目数据..."
          @selection-change="handleProjectSelectionChange"
      >
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column
            type="index"
            label="序号"
            width="60"
            align="center">
        </el-table-column>
        <el-table-column
            prop="projectName"
            label="项目名称">
        </el-table-column>
        <el-table-column
            prop="projectType"
            label="类型">
        </el-table-column>
        <el-table-column
            prop="declareLevel"
            label="申报等级">
          <template slot-scope="scope">
            <el-tag :type="scope.row.declareLevel === '一等奖' ? 'primary' :
                                   scope.row.declareLevel === '二等奖' ? 'success' : 'info'">
              {{ scope.row.declareLevel }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
            prop="specialty"
            label="所属专业组">
        </el-table-column>
        <el-table-column
            prop="status"
            label="状态">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 1 ? 'warning' : 'success'">
              {{ scope.row.status === 1 ? '未评审' : '已评审' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
            label="操作"
            width="120">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-view" @click="viewProjectDetail(scope.row)">查看
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" style="color: #ff4d4f;"
                       @click="deleteProject(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          @size-change="handleProjectSizeChange"
          @current-change="handleProjectCurrentChange"
          :current-page="projectCurrentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="projectPageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <!-- 导入项目对话框 -->
    <el-dialog
        title="导入项目"
        :visible.sync="importDialogVisible"
        width="800px"
        top="10%"
    >
      <div class="import-dialog-content">
        <!-- 奖项列表 - 移除分页 -->
        <el-table
            :data="availableAwards"
            border
            style="width: 100%;"
            v-loading="awardLoading"
            element-loading-text="正在加载奖项数据..."
            @selection-change="handleAwardSelectionChange"
        >
          <el-table-column
              type="selection"
              width="55">
          </el-table-column>
          <el-table-column
              type="index"
              label="序号"
              width="60"
              align="center">
          </el-table-column>
          <el-table-column
              prop="projectName"
              label="项目名称"
              width="250">
          </el-table-column>
          <el-table-column
              prop="specialty"
              label="专业组">
          </el-table-column>
          <el-table-column
              prop="year"
              label="年度">
          </el-table-column>
          <el-table-column
              prop="declareLevel"
              label="申报等级">
            <template slot-scope="scope">
              <el-tag :type="scope.row.declareLevel === '一等奖' ? 'primary' :
                                     scope.row.declareLevel === '二等奖' ? 'success' : 'info'">
                {{ scope.row.declareLevel }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="importDialogVisible = false">取消</el-button>
        <el-button
            type="primary"
            @click="confirmImportProjects"
            :disabled="selectedAwards.length === 0 || isImporting"
        >
          <i v-if="isImporting" class="el-icon-loading"></i>
          导入选中的 {{ selectedAwards.length }} 个项目
        </el-button>
      </div>
    </el-dialog>

    <!-- 项目详情对话框 -->
    <el-dialog
        title="项目详情"
        :visible.sync="projectDialogVisible"
        width="70%"
        top="5%"
        :fullscreen="false"
        :modal="true"
    >
      <div v-if="currentProject" class="detail-dialog-content">
        <!-- 项目标题和状态 -->
        <div class="project-header">
          <h3 class="project-title">{{ currentProject.projectName }}</h3>
          <el-tag
              :type="currentProject.status === 1 ? 'warning' : 'success'"
              class="project-status-tag"
          >
            {{ currentProject.status === 1 ? '未评审' : '已评审' }}
          </el-tag>
        </div>

        <!-- 项目基本信息 -->
        <div class="project-info-section">
          <h4 class="section-title">
            <i class="el-icon-info"></i> 项目基本信息
          </h4>
          <el-descriptions :column="1" border class="project-info">
            <el-descriptions-item label="项目名称">{{ currentProject.projectName }}</el-descriptions-item>
            <el-descriptions-item label="申报等级">{{ currentProject.declareLevel }}</el-descriptions-item>
            <el-descriptions-item label="所属专业组">{{ currentProject.specialty }}</el-descriptions-item>
            <el-descriptions-item label="报奖类型">{{ currentProject.projectType }}</el-descriptions-item>
            <el-descriptions-item label="评审状态">{{
                currentProject.status === 1 ? '未评审' : '已评审'
              }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 项目背景 -->
        <div class="project-detail-section">
          <h4 class="section-title">
            <i class="el-icon-document"></i> 立项背景及意义
          </h4>
          <el-card class="detail-card">
            <p class="preformatted-text">{{ currentProject.projectBg || '无相关信息' }}</p>
          </el-card>
        </div>

        <!-- 创新点 -->
        <div class="project-detail-section">
          <h4 class="section-title">
            <i class="el-icon-sunny"></i> 科技创新点
          </h4>
          <el-card class="detail-card">
            <p class="preformatted-text">{{ currentProject.innovation || '无相关信息' }}</p>
          </el-card>
        </div>

        <!-- 经济效益 -->
        <div class="project-detail-section">
          <h4 class="section-title">
            <i class="el-icon-money"></i> 经济效益
          </h4>
          <el-card class="detail-card">
            <p class="preformatted-text">{{ currentProject.economicBenefit || '无相关信息' }}</p>
          </el-card>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="projectDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
// 导入新的接口
// 导入新的接口
import {getUnallocatedAwardList} from '@/api/award';
import {
  getProjectPage,
  getProjectById,
  saveProjectBatch,
  deleteProject,
  deleteProjectBatch
} from '@/api/project';

export default {
  data() {
    return {
      // 项目列表数据
      projects: [],
      total: 0,
      loading: false,

      // 独立的搜索条件变量
      selectedSpecialty: '',    // 选中的专业组
      selectedLevel: '',        // 选中的申报等级
      searchKeyword: '',        // 搜索关键词

      // 分页参数
      projectCurrentPage: 1,
      projectPageSize: 10,

      // 选中的项目
      selectedProjectRows: [],

      // 导入项目相关 - 移除分页相关参数
      importDialogVisible: false,
      awardList: [],           // 存储所有未分配奖项数据
      awardLoading: false,
      selectedAwards: [],
      isImporting: false,

      // 项目详情相关
      projectDialogVisible: false,
      currentProject: {}
    }
  },
  computed: {
    // 过滤后的项目列表（根据搜索条件）
    filteredProjects() {
      return this.projects.filter(project => {
        const matchesSpecialty = !this.selectedSpecialty || project.specialty === this.selectedSpecialty;
        const matchesLevel = !this.selectedLevel || project.declareLevel === this.selectedLevel;
        const matchesKeyword = !this.searchKeyword ||
            project.projectName.includes(this.searchKeyword);

        return matchesSpecialty && matchesLevel && matchesKeyword;
      });
    },
    // 过滤掉已导入项目的可用奖项列表
    availableAwards() {
      // 获取已导入项目的名称列表
      const existingProjectNames = this.projects.map(p => p.projectName);

      // 只显示不在已导入项目列表中的奖项
      return this.awardList.filter(award =>
          !existingProjectNames.includes(award.projectName)
      );
    }
  },
  created() {
    // 页面加载时获取项目列表
    this.loadProjectData();
  },
  methods: {
    // 加载项目数据
    loadProjectData() {
      this.loading = true;

      const params = {
        pageNum: this.projectCurrentPage,
        pageSize: this.projectPageSize,
        filters: {
          specialty: this.selectedSpecialty,
          level: this.selectedLevel,
          name: this.searchKeyword
        }
      };

      getProjectPage(params)
          .then(response => {
            if (response.code === '200' && response.data) {
              this.projects = response.data.records || [];
              this.total = response.data.total || 0;
            } else {
              this.$message.error('获取项目数据失败: ' + (response.msg || '未知错误'));
              this.projects = [];
              this.total = 0;
            }
            this.loading = false;
          })
          .catch(error => {
            console.error('获取项目数据出错:', error);
            this.$message.error('获取项目数据时发生错误');
            this.loading = false;
          });
    },

    // 处理筛选条件变化
    handleFilterChange() {
      this.projectCurrentPage = 1;
      this.loadProjectData();
    },

    // 处理搜索输入
    handleSearchInput(val) {
      // 延迟搜索，避免输入过快导致频繁请求
      clearTimeout(this.searchTimer);
      this.searchTimer = setTimeout(() => {
        this.projectCurrentPage = 1;
        this.loadProjectData();
      }, 500);
    },

    // 分页相关方法
    handleProjectSizeChange(val) {
      this.projectPageSize = val;
      this.projectCurrentPage = 1;
      this.loadProjectData();
    },
    handleProjectCurrentChange(val) {
      this.projectCurrentPage = val;
      this.loadProjectData();
    },

    // 处理项目选择变化
    handleProjectSelectionChange(selection) {
      this.selectedProjectRows = selection;
    },

    // 打开导入项目对话框
    openImportDialog() {
      this.importDialogVisible = true;
      this.selectedAwards = [];
      this.loadAwardData();  // 加载所有未分配奖项
    },

    // 加载奖项数据 - 修改为使用新接口且不分页
    loadAwardData() {
      this.awardLoading = true;

      // 可以根据需要添加筛选条件
      const filters = {
        // 这里可以添加额外的筛选条件
        // status: 50  // 接口默认已经是status=50，所以可以省略
      };

      // 调用新的不分页接口
      getUnallocatedAwardList(filters)
          .then(response => {
            if (response.code === '200') {
              // 假设接口返回的数据直接是数组
              this.awardList = response.data || [];
            } else {
              this.$message.error('获取奖项数据失败: ' + (response.msg || '未知错误'));
              this.awardList = [];
            }
            this.awardLoading = false;
          })
          .catch(error => {
            console.error('获取奖项数据出错:', error);
            this.$message.error('获取奖项数据时发生错误');
            this.awardLoading = false;
          });
    },

    // 处理奖项选择变化
    handleAwardSelectionChange(selection) {
      this.selectedAwards = selection;
    },

    // 确认导入选中的项目
    confirmImportProjects() {
      if (this.selectedAwards.length === 0) return;

      this.isImporting = true;

      // 转换奖项数据为项目数据格式
      const projectsToImport = this.selectedAwards.map(award => ({
        projectName: award.projectName,
        declareLevel: award.declareLevel,
        specialty: award.specialty,
        projectBg: award.projectBg,
        innovation: award.innovation,
        economicBenefit: award.economicBenefit,
        projectType: award.type,
        status: 1
      }));

      // 调用批量保存接口
      saveProjectBatch(projectsToImport)
          .then(response => {
            if (response.code === '200') {
              this.$message.success(`成功导入 ${this.selectedAwards.length} 个项目`);
              this.importDialogVisible = false;
              // 重新加载项目数据和奖项数据
              this.loadProjectData();
            } else {
              this.$message.error('导入项目失败: ' + (response.msg || '未知错误'));
            }
            this.isImporting = false;
          })
          .catch(error => {
            console.error('导入项目出错:', error);
            this.$message.error('导入项目时发生错误');
            this.isImporting = false;
          });
    },

    // 查看项目详情
    viewProjectDetail(project) {
      // 获取项目详情
      getProjectById(project.id)
          .then(response => {
            if (response.code === '200' && response.data) {
              this.currentProject = {...response.data};
              this.projectDialogVisible = true;
            } else {
              this.$message.error('获取项目详情失败: ' + (response.msg || '未知错误'));
            }
          })
          .catch(error => {
            console.error('获取项目详情出错:', error);
            this.$message.error('获取项目详情时发生错误');
          });
    },

    // 删除单个项目
    deleteProject(project) {
      this.$confirm(`确定要删除项目"${project.projectName}"吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteProject(project.id)
            .then(response => {
              if (response.code === '200') {
                this.$message.success('项目已删除');
                // 重新加载项目数据
                this.loadProjectData();
              } else {
                this.$message.error('删除项目失败: ' + (response.msg || '未知错误'));
              }
            })
            .catch(error => {
              console.error('删除项目出错:', error);
              this.$message.error('删除项目时发生错误');
            });
      }).catch(() => {
        // 取消删除
      });
    },

    // 批量删除项目
    batchDeleteProjects() {
      if (this.selectedProjectRows.length === 0) return;

      this.$confirm(`确定要删除选中的 ${this.selectedProjectRows.length} 个项目吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = this.selectedProjectRows.map(project => project.id);
        deleteProjectBatch(ids)
            .then(response => {
              if (response.code === '200') {
                this.$message.success(`已删除选中的 ${this.selectedProjectRows.length} 个项目`);
                this.selectedProjectRows = [];
                // 重新加载项目数据
                this.loadProjectData();
              } else {
                this.$message.error('批量删除项目失败: ' + (response.msg || '未知错误'));
              }
            })
            .catch(error => {
              console.error('批量删除项目出错:', error);
              this.$message.error('批量删除项目时发生错误');
            });
      }).catch(() => {
        // 取消删除
      });
    }
  }
}
</script>

<style scoped>
.filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-group {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}

.filter-group .el-select {
  width: 180px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.card-container {
  background: #fff;
  padding: 15px;
  border-radius: 4px;
}

.import-dialog-content {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 10px;
}

::v-deep .el-dialog__body {
  padding: 20px;
  max-height: 80vh;
  overflow-y: auto;
  box-sizing: border-box;
}

/* 项目详情对话框样式 */
.detail-dialog-content {
  height: 100%;
  overflow-y: auto;
  box-sizing: border-box;
}

.project-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e8e8e8;
}

.project-title {
  margin: 0;
  color: #1f2329;
  font-size: 1.2rem;
}

.project-status-tag {
  margin-top: 3px;
}

.project-info-section,
.project-detail-section {
  margin-bottom: 25px;
}

.section-title {
  font-size: 1rem;
  color: #1890ff;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}

.section-title i {
  margin-right: 8px;
}

.detail-card {
  border-radius: 4px;
}

.detail-card p {
  line-height: 1.8;
  margin: 0;
  color: #4e5969;
}

/* 支持文本换行的样式 */
.preformatted-text {
  white-space: pre-wrap;
  word-wrap: break-word;
}

.project-info {
  margin-bottom: 10px;
}

/* 调整详情对话框中描述项的样式 */
::v-deep .el-descriptions-item__label {
  font-weight: 500;
  color: #4e5969;
}

::v-deep .el-descriptions-item__content {
  color: #1f2329;
}
</style>
